package com.itheima.edu.info.manager.dao;

import com.itheima.edu.info.manager.domain.Student;

public class StudentDao implements BaseStudentDao{
    // 1. 创建学生对象数组
    private static Student[] students = new Student[5];

    static {
        Student stu1 = new Student("heima001", "张三", "23", "1999-11-11");
        Student stu2 = new Student("heima002", "李四", "24", "2000-11-11");

        students[0] = stu1;
        students[1] = stu2;
    }

    @Override
    public boolean addStudent(Student stu) {
        // 2. 添加学生到数组
        // 2.1 定义变量 index 为-1，假设数组已经全部存满，没有 null 的元素
        int index = -1;
        // 2.2 遍历数组取出每一个元素，判断是否为 null
        for (int i = 0; i < students.length; i++) {
            Student student = students[i];
            if (student == null) {
                index = i;
                // 2.3 如果为 null，让 index 变量记录当前索引位置，并使用 break 结束循环遍历
                break;
            }
        }
        // 3. 返回是否添加成功的 boolean 类型状态
        if (index == -1) {
            // 装满了
            return false;
        } else {
            students[index] = stu;
            return true;
        }
    }

    @Override
    public Student[] findAllStudent() {
        return students;
    }

    @Override
    public void deleteStudentById(String delId) {
        // 1. 查找 id 在容器中所在的位置
        int index = getIndex(delId);

        // 2. 使用 null 覆盖索引位置
        students[index] = null;
    }

    @Override
    public int getIndex(String id) {
        int index = -1;
        for (int i = 0; i < students.length; i++) {
            Student stu = students[i];
            if (stu != null && stu.getId().equals(id)) {
                index = i;
                break;
            }
        }
        return index;
    }

    @Override
    public void updateStudent(Student stu) {
        int index = getIndex(stu.getId());
        students[index] = stu;
    }

    @Override
    public void updateStudent(String updateId, Student stu) {
        int index = getIndex(updateId);
        students[index] = stu;
    }
}
